package com.yt.Insurance.server.common.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yt.common.utils.StrUtils;
import com.yt.common.utils.WebUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @Description ：
 * @Author ： mx.li
 * @Date ： 2018/07/27 15:25
 */
@Slf4j
//@WebFilter(urlPatterns = "/*", filterName = "responseLogFilter")
//@Component
public class ResponseFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        JSONObject json = new JSONObject();
        json.put("ip:", WebUtils.getClientIP((HttpServletRequest) request));
        json.put("url:", ((HttpServletRequest) request).getRequestURI());
        json.put("params", JSON.toJSONString(request.getParameterMap()));
        ResponseWrapper responseWrapper = new ResponseWrapper((HttpServletResponse) response);
        filterChain.doFilter(request, responseWrapper);
        String responseContent = new String(responseWrapper.getDataStream());
        json.put("result", responseContent);
        log.info("----params:"+json.toJSONString());
        if (StrUtils.isNotEmpty(responseContent)) {
            byte[] responseToSend = responseContent.getBytes(StandardCharsets.UTF_8);
            response.setContentLength(responseToSend.length);
            response.getOutputStream().write(responseToSend);
        }
    }

    @Override
    public void destroy() {

    }
}
